package com.iye.puretennis.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import cn.jpush.android.api.JPushInterface;
import com.iye.puretennis.R;
import com.iye.puretennis.custom.BaseActivity;
import com.iye.puretennis.custom.HuaWenHuPoEditText;
import com.iye.puretennis.custom.UploadImagePopupWindow;
import com.iye.puretennis.domain.Gender;
import com.iye.puretennis.domain.UrlSuffix;
import com.iye.puretennis.helper.Constant;
import com.iye.puretennis.helper.RemoteUrlCollections;
import com.iye.puretennis.helper.ServerAccessHelper;
import com.iye.puretennis.utils.ImageUtils;
import com.iye.puretennis.utils.StringUtils;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.UiError;
import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;

/**
 * Created with IntelliJ IDEA.
 * User: jing wu
 * Date: 2015/1/12
 * Time: 9:35
 */
public class RegisterActivity extends BaseActivity implements IUiListener {
    public static final String TAG = "register";

    private RadioGroup genderRadioGroup;
    private RadioButton maleRadio;
    private ImageView uploadImageView;
    
    private String imageBase64Byte;

    private AlertDialog.Builder builder;

    public void back(View view){
        onBackPressed();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.register);

        genderRadioGroup = (RadioGroup) findViewById(R.id.profile_gender_group);
        final RadioButton femaleRadio = (RadioButton) findViewById(R.id.profile_gender_female);
        maleRadio = (RadioButton) findViewById(R.id.profile_gender_male);

        handleGenderIcon(femaleRadio,maleRadio,false);
        genderRadioGroup.check(femaleRadio.getId());

        uploadImageView = (ImageView) findViewById(R.id.profile_image_view);

        int layout = height / 3;

        ViewGroup.LayoutParams layoutParams = uploadImageView.getLayoutParams();

        layoutParams.width = layout;

        layoutParams.height = layout;

        uploadImageView.setLayoutParams(layoutParams);

        Resources resources = getResources();
        Bitmap bmp = BitmapFactory.decodeResource(resources, R.drawable.avatar);
        imageBase64Byte = ImageUtils.bitmapToBase64(bmp);
        uploadImageView.setImageBitmap(ImageUtils.toRoundBitmap(bmp));

        uploadImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int vid = v.getId();
                if (vid == uploadImageView.getId()) {
                    showPopUp();
                }
            }
        });

        //add radio group checked change listener
        genderRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                boolean maleChecked = (checkedId == maleRadio.getId());
                handleGenderIcon(femaleRadio, maleRadio, maleChecked);
            }
        });

        builder = new AlertDialog.Builder(RegisterActivity.this);
    }

    //update the check -  unChecked icon
    private void handleGenderIcon(RadioButton femaleRadioButton, RadioButton maleRadioButton, boolean maleChecked) {

        if (maleChecked) {
            Drawable maleRadioChecked = getResources().getDrawable(R.drawable.male_checked);
            maleRadioChecked.setBounds(0, 0, maleRadioChecked.getMinimumWidth(), maleRadioChecked.getMinimumHeight());
            maleRadioButton.setCompoundDrawables(maleRadioChecked, null, null, null);

            Drawable femaleRadioUnChecked = getResources().getDrawable(R.drawable.female_unchecked);
            femaleRadioUnChecked.setBounds(0, 0, femaleRadioUnChecked.getMinimumWidth(), femaleRadioUnChecked.getMinimumHeight());
            femaleRadioButton.setCompoundDrawables(femaleRadioUnChecked, null, null, null);
        } else {
            Drawable femaleRadioChecked = getResources().getDrawable(R.drawable.female_checked);
            femaleRadioChecked.setBounds(0, 0, femaleRadioChecked.getMinimumWidth(), femaleRadioChecked.getMinimumHeight());
            femaleRadioButton.setCompoundDrawables(femaleRadioChecked, null, null, null);

            Drawable maleRadioUnChecked = getResources().getDrawable(R.drawable.male_unchecked);
            maleRadioUnChecked.setBounds(0, 0, maleRadioUnChecked.getMinimumWidth(), maleRadioUnChecked.getMinimumHeight());
            maleRadioButton.setCompoundDrawables(maleRadioUnChecked, null, null, null);
        }
    }


    private boolean validate(String nickname, String password) {
        boolean result = true;
        String message = null;


        if (!StringUtils.hasText(password)) {
            result = false;
            message = "请输入密码！";

        } else {
            if (password.length() < 6) {
                result = false;
                message = "密码不少于6位！";

            }
        }

        if (!StringUtils.hasText(nickname)) {
            result = false;
            message = "请输入昵称！";
        }

        if (!result) {
            builder.setMessage(message);
            builder.show();
        }
        return result;
    }


    /**
     * register the user in system
     */
    public void register(View view) {


        HuaWenHuPoEditText nickNameTag = (HuaWenHuPoEditText) findViewById(R.id.nickname);
        HuaWenHuPoEditText passwordText = (HuaWenHuPoEditText) findViewById(R.id.password);

        final String nickname = nickNameTag.getText().toString();
        final String password = passwordText.getText().toString();

        if (validate(nickname, password)) {
            RadioButton genderBtn = (RadioButton) findViewById(genderRadioGroup.getCheckedRadioButtonId());
            String gender = Gender.FEMALE.name();
            if (maleRadio.getId() == genderBtn.getId()) {
                gender = Gender.MALE.name();
            }
            final String finalGender = gender;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    StringEntity paramEntity;
                    String result;
                    JSONObject jsonObj;
                    try {
                        jsonObj = new JSONObject();

                        jsonObj.put("nickname", nickname);

                        paramEntity = new StringEntity(jsonObj.toString(), Constant.CHARSET_UTF8);

                        result = ServerAccessHelper.queryStringForPost(RemoteUrlCollections.getUrl(UrlSuffix.USER_CHECK_UNIQUE), null, paramEntity);

                        if ("false".equals(result)) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    builder.setMessage("该昵称已被使用，请重新输入昵称！");
                                    builder.show();
                                }
                            });

                        } else {
                            jsonObj = new JSONObject();
                            jsonObj.put("nickname", nickname);
                            jsonObj.put("password", password);
                            jsonObj.put("gender", finalGender);
                            jsonObj.put("idolGuid", "");
                            jsonObj.put("imageBase64Byte", imageBase64Byte);
                            paramEntity = new StringEntity(jsonObj.toString(), Constant.CHARSET_UTF8);
                            result = ServerAccessHelper.queryStringForPost(RemoteUrlCollections.getUrl(UrlSuffix.REGISTER), null, paramEntity);
                            if (!Constant.RESPONSE_BADLY.equals(result)) {
                                String rev = ServerAccessHelper.login(nickname, password);
                                if (StringUtils.hasText(rev)) {
                                    JSONObject loginJson = new JSONObject(rev);
                                    String guid = loginJson.getString("guid");
                                    String token = loginJson.getString("token");
                                    boolean setup = loginJson.getBoolean("setup");
                                    dbManager.login(guid, token, setup ? 1 : 0);
                                    //start the profile activity
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Intent intent = new Intent(RegisterActivity.this, MainTabsActivity.class);
                                            startActivity(intent);
                                            overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
                                        }
                                    });
                                }
                            }
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 拍照或者读取相册缩放图片
        boolean pickPhoto = requestCode == Constant.PICK_PHOTO;
        boolean takePhoto = requestCode == Constant.TAKE_PHOTO;
        if (takePhoto || pickPhoto) {
            Intent intent = new Intent(Constant.SYSTEM_ACTIVITY_CROP);
            Uri uri = null;
            if (data != null) {
                uri = data.getData();
            } else if (takePhoto) {
                uri = Uri.fromFile(new File(UploadImagePopupWindow.FILE_PATH));
            }
            if (uri != null) {
                intent.setDataAndType(uri, Constant.IMAGE_UNSPECIFIED);

                intent.putExtra("crop", "true");
                intent.putExtra("aspectX", 1);
                intent.putExtra("aspectY", 1);
                intent.putExtra("outputX", Constant.PROFILE_IMAGE_WIDTH);
                intent.putExtra("outputY", Constant.PROFILE_IMAGE_HEIGHT);
                intent.putExtra("noFaceDetection", true);
                intent.putExtra("return-data", true);
                startActivityForResult(intent, Constant.CROP_PHOTO);
            }
        }

        if (requestCode == Constant.CROP_PHOTO && data != null) {
            handleProfileImage(data);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void handleProfileImage(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap bitmap = extras.getParcelable("data");
            Bitmap compress = ImageUtils.compressImage(bitmap, 200);
            compress = ImageUtils.roundedCornerBitmap(compress, 5);
            this.uploadImageView.setImageBitmap(ImageUtils.toRoundBitmap(compress));
            imageBase64Byte = ImageUtils.bitmapToBase64(compress);
        }

    }

    /**
     * ***********************Remote server request part********************************
     */
    private void showPopUp() {
        PopupWindow popupWindow = new UploadImagePopupWindow(this);
        popupWindow.showAtLocation(findViewById(R.id.register), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }


    @Override
    public void onComplete(Object o) {

    }

    @Override
    public void onError(UiError uiError) {

    }

    @Override
    public void onCancel() {

    }


    @Override
    protected void onResume() {

        super.onResume();

        JPushInterface.onResume(this);

    }

    @Override
    protected void onPause() {

        super.onPause();

        JPushInterface.onPause(this);

    }


}
